//
//  DatabaseManager.m
//  999-考勤定位
//
//  Created by 李晓东 on 2018/4/8.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "DatabaseManager.h"
#import <sqlite3.h>


static NSString *tempName;
@interface DatabaseManager ()

@end

@implementation DatabaseManager

// 说明.用 static 修饰变量的作用.
// 用 static 修饰的变量,在这个方法结束后,任然存在在内存中,只是外部没法再访问.只有等下次再调用这个单例方法时,才能访问到这个已经初始化过的变量
// 假设在不使用 static 修饰时,每当其他函数使用完这个变量后,那这个变量就会销毁掉.等下次再使用时,还会再初始化一次.等于这个单例作用失效了
+ (instancetype)shareDatabaseManager {
    static dispatch_once_t onceToken;
    static DatabaseManager *database;
    dispatch_once(&onceToken, ^{
        database = [[DatabaseManager alloc]init];
        [database createTable];
    });
    return database;
    
}

- (void)createTable {
    sqlite3 *database;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"LocationDatabase"];
    sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, NULL);
    
    const char *sql = "create table location (id integer primary key autoincrement , weekday integer, office_hour integer, off_hour integer);";
    char *error;
    int flag = sqlite3_exec(database, sql, NULL, NULL, &error);
    if (flag == SQLITE_OK) {
        NSLog(@"建表成功");
    }
}

- (void)saveInLocationRule:(NSDictionary *)dict {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"LocationDatabase"];
    sqlite3 *database;
    sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil);

    sqlite3_stmt *stmt;
    const char *sql = "insert into location values (null, ?, ?, ?)";
    int insertResult = sqlite3_prepare_v2(database, sql, -1, &stmt, nil);
    if (insertResult == SQLITE_OK) {
        NSNumber *number = dict[@"weekday"];
        sqlite3_bind_int(stmt, 1, [[number stringValue]intValue]);
        sqlite3_bind_int(stmt, 2, [dict[@"office_hour"]intValue]);
        sqlite3_bind_int(stmt, 3, [dict[@"off_hour"]intValue]);
        
        sqlite3_step(stmt);
        
    }
    sqlite3_finalize(stmt);
    
    sqlite3_close_v2(database);
}

- (void)updateInLocationRule: (NSDictionary *)dict {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"LocationDatabase"];
    sqlite3 *database;
    sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil);
    
    sqlite3_stmt *stmt;
    const char *sql = "update location set weekday = ?, office_hour = ?, off_hour = ?;";
    int flag = sqlite3_prepare_v2(database, sql, -1, &stmt, nil);
    if (flag == SQLITE_OK) {
        sqlite3_bind_int(stmt, 1, [dict[@"weekday"] intValue]);
        sqlite3_bind_int64(stmt, 2, [dict[@"office_hour"] integerValue]);
        sqlite3_bind_int64(stmt, 3, [dict[@"off_hour"] integerValue]);
        
        sqlite3_step(stmt);
    }
    sqlite3_finalize(stmt);
    sqlite3_close_v2(database);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeNotificationSetting" object:self userInfo:@{@"offich_hour":[NSNumber numberWithInteger:[dict[@"office_hour"] integerValue]], @"off_hour":[NSNumber numberWithInteger:[dict[@"off_hour"] integerValue]], @"weekday": [NSNumber numberWithInteger:[dict[@"weekday"] integerValue]]}];
}

- (void)queryInLocationRule {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"LocationDatabase"];
    sqlite3 *database;
    sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, nil);
    char *sql = "select * from location;";
    sqlite3_stmt *stmt;
    int flag = sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);
    if (flag == SQLITE_OK) {
        
        NSMutableArray<NSDictionary *> *resultArray = [NSMutableArray array];
        while (sqlite3_step(stmt) == SQLITE_ROW ) {
            NSDictionary *dict = @{@"id": [NSNumber numberWithInt:sqlite3_column_int(stmt, 0)], @"weekday": [NSNumber numberWithInteger:sqlite3_column_int(stmt, 1)], @"office_hour": [NSNumber numberWithInteger:sqlite3_column_int64(stmt, 2)], @"off_hour":[NSNumber numberWithInteger:sqlite3_column_int64(stmt, 3)]};
            [resultArray addObject:dict];
            
            
        }
        self.getLocationRuleBlock(resultArray);
    }
    
}
@end
